﻿using System;
using System.Collections.Generic;
using System.Text;

namespace IOP.OpenType.Tables
{
    /// <summary>
    /// 
    /// </summary>
    public class CmapSubTable2 : CmapSubTable
    {
        /// <summary>
        /// Array that maps high bytes to subHeaders: value is index * 8
        /// </summary>
        public ushort[] SubHeaderKeys { get; set; } = new ushort[256];
        /// <summary>
        /// Variable length array of subHeader structures
        /// </summary>
        public SubHeader[] SubHeaders { get; set; }
        /// <summary>
        /// Variable length array containing subarrays
        /// </summary>
        public ushort[] GlyphIndexArray { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public override uint GetGlyphId(char c)
        {
            int height = c >> 8;
            ushort i = SubHeaderKeys[height];
            ushort k = (ushort)(SubHeaderKeys[height] / 8);
            if (k == 0) return GlyphIndexArray[i];
            SubHeader header = SubHeaders[i];
            ushort j = (byte)c;
            var min = header.FirstCode;
            var max = header.FirstCode + header.EntryCount;
            if (j < min || j > max) return 0;
            var p = GlyphIndexArray[j - header.FirstCode];
            if (p == 0) return p;
            else return (uint)((p + header.IdDelta) & 0xffff);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override char GetMaxCharacter()
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override char GetMinCharacter()
        {
            return (char)0;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public struct SubHeader
    {
        /// <summary>
        /// 
        /// </summary>
        public ushort FirstCode;
        /// <summary>
        /// 
        /// </summary>
        public ushort EntryCount;
        /// <summary>
        /// 
        /// </summary>
        public short IdDelta;
        /// <summary>
        /// 
        /// </summary>
        public ushort IdRangeOffset;
    }
}
